import {_decorator, Camera, Component, EventTouch, math, Node, Vec2, Vec3, Touch} from 'cc';
import {lobby} from "db://assets/script/lobby";

const {ccclass, property} = _decorator;

@ccclass('PinchZoom')
export class PinchZoom extends Component {

    // 用于控制缩放的节点，比如摄像机或者地图根节点
    @property(Node)
    targetNode!: Node;

    // 缩放限制
    @property
    minScale: number = 0.5;
    @property
    maxScale: number = 3.0;

    @property
    public zoomSensitivity: number = 5;

    @property
    public minHeight: number = 440;

    @property
    public maxHeight: number = 1240;

    // 内部状态变量
    private _isPinching: boolean = false;

    private _initialFOV: number = 45;
    _lastPinchDistance: number | null = null

    onLoad() {
        // 如果未指定目标节点，则默认缩放此脚本所在的节点
        if (!this.targetNode) {
            this.targetNode = this.node;
        }
        // // 保存初始缩放值
        // this._startScale = this.targetNode.scale.x;
    }

    start() {
        // 注册触摸事件监听器
        this.node.on(Node.EventType.TOUCH_START, this._onTouchStart, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
        this.node.on(Node.EventType.TOUCH_END, this._onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this._onTouchEnd, this);
    }

    onDestroy() {
        // 组件销毁时，取消事件监听
        this.node.off(Node.EventType.TOUCH_START, this._onTouchStart, this);
        this.node.off(Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
        this.node.off(Node.EventType.TOUCH_END, this._onTouchEnd, this);
        this.node.off(Node.EventType.TOUCH_CANCEL, this._onTouchEnd, this);
    }

    private _onTouchStart(event: EventTouch) {
        if (!this.targetNode || !this.targetNode.isValid) return
        const touches = event.getAllTouches();
        console.log('touch length:', touches);
        // 当屏幕上有两个触摸点时，开始缩放模式
        if (touches.length == 2) {
            event.preventSwallow = false;
            this._isPinching = true;
            // 计算两指之间的初始距离
        } else {
            event.preventSwallow = true;
        }
    }

    private _onTouchMove(event: EventTouch) {
        if (!this.targetNode || !this.targetNode.isValid) return
        // 只有在双指缩放状态下才进行处理
        if (!this._isPinching) {
            event.preventSwallow = true
            return
        }

        const touches = event.getAllTouches();
        if (touches.length != 2) {
            event.preventSwallow = true;
            return
        }
        event.preventSwallow = false;
        this.handlePinchZoom(touches);
        // 计算当前两指之间的距离
        // const currentDistance = this._getDistance(touches[0].getLocation(), touches[1].getLocation());
        // // 计算距离比例（当前距离 / 初始距离）
        // let scaleRatio = currentDistance / this._startDistance;
        // // 计算新的缩放值：初始缩放值 * 比例
        // let newScale = this._startScale * scaleRatio;
        //
        // // 应用缩放限制
        // newScale = Math.max(this.minScale, Math.min(this.maxScale, newScale));
        //
        // // 将新的缩放值统一应用到节点的三个轴上，保持等比例缩放
        // this.targetNode.setScale(newScale, newScale, newScale);
    }

    private _onTouchEnd(event: EventTouch) {
        if (!this.targetNode || !this.targetNode.isValid) return
        const touches = event.getAllTouches();
        // 当屏幕上触摸点数量少于两个时，结束缩放模式
        if (touches.length < 2) {
            this._isPinching = false;
            this._lastPinchDistance = 0;
        }
        event.preventSwallow = true;
    }

    handlePinchZoom(touches: Touch[]) {
        if (touches.length < 2) return;

        // 计算两指中心点（用于后续的焦点调整）
        const center = this.calculateTouchCenter(touches[0], touches[1]);

        // 计算距离变化
        const currentDistance = this.calculateTouchDistance(touches[0], touches[1]);
        const startDistance = this._lastPinchDistance || currentDistance;

        // 计算缩放比例
        const zoomDelta = (startDistance - currentDistance) * this.zoomSensitivity * 0.1;

        // 调整摄像机高度
        this.adjustCameraHeight(zoomDelta, center);

        this._lastPinchDistance = currentDistance;
    }


    // 调整摄像机高度（带焦点）
    adjustCameraHeight(delta: number, focusPoint?: Vec3) {
        // const oldHeight = lobby.instance.camera.orthoHeight;
        lobby.instance.camera.orthoHeight = math.clamp(
            lobby.instance.camera.orthoHeight + delta,
            this.minHeight,
            this.maxHeight
        );
    }

    // 计算两指中心点
    private calculateTouchCenter(touch1: Touch, touch2: Touch): Vec3 {
        const pos1 = touch1.getLocation();
        const pos2 = touch2.getLocation();

        return new Vec3(
            (pos1.x + pos2.x) / 2,
            (pos1.y + pos2.y) / 2,
            0
        );
    }

    // 计算两指距离
    private calculateTouchDistance(touch1: Touch, touch2: Touch): number {
        const pos1 = touch1.getLocation();
        const pos2 = touch2.getLocation();
        return Vec2.distance(pos1, pos2);
    }

}